import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'

export function useTable() {
    const gridOptions = reactive<any>({
        border: true,
        columnConfig: {
            resizable: true,
        },
        columns: [
            // { slots: { checkbox: 'checkbox_cell', header: 'checkbox_header' }, type: 'checkbox', width: 60 },
            { field: 'enterpriseId', title: '企业号', width: 70 },
            { field: 'enterpriseName', title: '企业名称', width: 200 },
            { field: 'status', slots: { default: 'status' }, title: '企业状态', width: 80 },
            { field: 'enterpriseShort', title: '企业简称', width: 150 },
            { field: 'enterpriseLevelId', slots: { default: 'enterpriseLevelId' }, title: '企业级别', width: 100 },
            { field: 'unifiedSocialCreditCode', title: '信用代码', width: 200 },
            { field: 'legalRepresentative', title: '企业法人', width: 90 },
            { field: 'cooperationType', slots: { default: 'cooperationType' }, title: '合作类型', width: 90 },
            { field: 'userName', title: '企业管理员', width: 90 },
            { field: 'createTime', title: '添加时间', width: 150 },
            { field: 'createdName', title: '添加人', width: 100 },
            { slots: { default: 'operate' }, title: '操作', width: 340, fixed: 'right' },
        ],
        data: [],
        editConfig: {
            mode: 'row',
            showStatus: true,
            trigger: 'manual',
        },
        height: 530,
        keepSource: true,
        loading: false,
        pagerConfig: {
            currentPage: 1,
            enabled: true,
            pageSize: 10,
            pageSizes: [10, 20, 50, 100, 200, 500],
            total: 0,
        },
        showOverflow: true,
        stripe: true,
    })

    const btns = [
        {
            label: '查看',
            text: true,
            value: 'view',
        },
        {
            label: '编辑',
            text: true,
            value: 'edit',
        },
        // {
        //     label: '删除',
        //     text: true,
        //     value: 'delete',
        // },
        {
            label: '组织机构',
            text: true,
            value: 'organization',
        },
    ]

    const addBtn: any = {
        label: '添加房交会管理员',
        text: true,
        value: 'add',
    }

    // 删除空属性
    const paramsIsNull = (obj: any) => {
        const _newPar = {}
        for (const key in obj) {
            if (
                (obj[key] === 0 || obj[key])
                && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== ''
            ) {
                _newPar[key] = obj[key]
            }
        }
        // 返回新对象
        return _newPar
    }

    // TODO:多条件查询方法 仅字符串对比 模糊匹配
    const useQuery = (data: any, params: any) => {
        const notNullParams = paramsIsNull(params)
        return data.filter((item) => {
            return Object.keys(notNullParams).every((key: string) => {
                if (key === 'createTime') {
                    const target = item[key] ? item[key].replace('T', ' ') : ''
                    const [start, end] = notNullParams[key]
                    const t = new Date(target).getTime()
                    const s = new Date(start).getTime()
                    const e = new Date(end).getTime()
                    return (
                        s <= t && e >= t
                    )
                }
                else {
                    // eslint-disable-next-line unicorn/prefer-includes
                    const flag = item[key] ? item[key].indexOf(notNullParams[key]) !== -1 : false
                    return (
                        item[key] !== undefined
                        && flag
                    )
                }
            })
        })
    }

    // 前端分页
    const usePage = (data: any, gridOptions: any) => {
        const { currentPage, pageSize } = gridOptions.pagerConfig
        const val = cloneDeep(data)
        const list = val.splice((currentPage - 1) * pageSize, pageSize)
        return {
            list,
            total: data.length,
        }
    }

    // 处理机构树
    const arrayToTree = (items, parentIdKey = 'parentId', idKey = 'id') => {
        const tree = []
        const childrenOf = {}
        items.forEach((item) => {
            const parentId = item[parentIdKey]
            if (parentId === 0) {
                tree.push(item)
            }
            else {
                if (!childrenOf[parentId]) {
                    childrenOf[parentId] = []
                }
                childrenOf[parentId].push(item)
            }
        })
        function findChildren(items) {
            return items.map((item) => {
                const foundChildren = childrenOf[item[idKey]] || []
                item.children = findChildren(foundChildren)
                item.disabled = item.status === '1'
                // item.hasChildren = item.children.length
                return item
            })
        }
        return findChildren(tree)
    }

    return { addBtn, arrayToTree, btns, gridOptions, usePage, useQuery }
}
